/*
 * @Author: ZhaoDong
 * @Date: 2022-07-06 22:50:11
 * @LastEditors: ZhaoDong
 * @LastEditTime: 2022-07-19 14:01:56
 * @Description: vite config
 */
import type { UserConfigExport, ConfigEnv } from 'vite';
import { resolve } from 'path';
import { loadEnv, defineConfig } from 'vite';
import { createVitePlugins } from './build/vite/plugin';
import { wrapperEnv } from './build/utils';

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir);
}

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  const isBuild = command === 'build';
  console.log('#isBuild:', isBuild);

  const root = process.cwd();

  const env = loadEnv(mode, root);

  const viteEnv = wrapperEnv(env);
  const { VITE_DROP_CONSOLE, VITE_PORT, VITE_OPEN = false, VITE_OUT_DIR } = viteEnv;

  console.log('##env', env);
  return defineConfig({
    resolve: {
      alias: [
        {
          find: /\/@\//,
          replacement: pathResolve('src') + '/'
        },
        {
          find: /\/#\//,
          replacement: pathResolve('types') + '/'
        }
      ]
    },
    css: {
      preprocessorOptions: {}
    },
    plugins: createVitePlugins(viteEnv, isBuild),
    server: {
      port: VITE_PORT,
      open: VITE_OPEN,
      cors: true,
      hmr: {
        host: 'localhost',
        port: VITE_PORT
      } //,
      // proxy: {
      //   '/api': {
      //     target: '192.168.1.102',
      //     changeOrigin: true,
      //     rewrite: (path: string) => path.replace(/^\/api/, '')
      //   }
      // }
    },
    esbuild: {
      pure: VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : []
    },
    build: {
      target: 'es2015',
      cssTarget: 'chrome80',
      outDir: VITE_OUT_DIR,
      brotliSize: false,
      chunkSizeWarningLimit: 2000
    }
  });
};
